package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate>dateList=new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }

        ArrayList<Double> turnoverList=new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime=LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime=LocalDateTime.of(date, LocalTime.MAX);
            Map map=new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover= reportMapper.sumturnoverByMap(map);
            turnoverList.add(turnover==null?0.0:turnover);
        }
        return new TurnoverReportVO().builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,",")).build();
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate>dateList=new ArrayList<>();
        ArrayList<Integer>newUserList=new ArrayList<>();
        ArrayList<Integer>totalUserList=new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        for (LocalDate date : dateList) {
            LocalDateTime beginTime=LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime=LocalDateTime.of(date, LocalTime.MAX);
            Map map=new HashMap();
            map.put("end",endTime);
            map.put("begin",beginTime);
            Integer newUser= reportMapper.countnewUserByMap(map);
            newUserList.add(newUser);
            Map map1=new HashMap();
            map1.put("end",endTime);
            Integer totalUser= reportMapper.countTotalUserByMap(map1);
            totalUserList.add(totalUser);
        }
        return new UserReportVO().builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,",")).build();
    }

    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate>dateList=new ArrayList<>();
        ArrayList<Integer>orderCountList=new ArrayList<>();
        ArrayList<Integer>validOrderCountList=new ArrayList<>();
        LocalDateTime beginTime1=LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime1=LocalDateTime.of(end, LocalTime.MAX);
        Map map1=new HashMap();
        map1.put("begin",beginTime1);
        map1.put("end",endTime1);
        Integer totalOrderCount= reportMapper.countOrderByMap(map1);
        map1.put("status",Orders.COMPLETED);
        Integer validOrderCount= reportMapper.countOrderByMap(map1);
        Double orderCompletionRate=validOrderCount.doubleValue()/totalOrderCount;
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        for (LocalDate date : dateList) {
            LocalDateTime beginTime=LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime=LocalDateTime.of(date, LocalTime.MAX);
            Map map=new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            Integer orderCount= reportMapper.countOrderByMap(map);
            orderCountList.add(orderCount);
            map.put("status",Orders.COMPLETED);
            Integer validOrderCount1= reportMapper.countOrderByMap(map);
            validOrderCountList.add(validOrderCount1);
        }
    return new OrderReportVO().builder()
            .dateList(StringUtils.join(dateList,","))
            .orderCountList(StringUtils.join(orderCountList,","))
            .validOrderCountList(StringUtils.join(validOrderCountList,","))
            .totalOrderCount(totalOrderCount)
            .validOrderCount(validOrderCount)
            .orderCompletionRate(orderCompletionRate).build();
    }

    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime=LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime=LocalDateTime.of(end, LocalTime.MAX);
        ArrayList<GoodsSalesDTO>list= reportMapper.getTop10();
        List<String> nameList = list.stream().map(goodsSalesDTO -> goodsSalesDTO.getName()).collect(Collectors.toList());
        List<Integer> numberList = list.stream().map(goodsSalesDTO -> goodsSalesDTO.getNumber()).collect(Collectors.toList());
        return new SalesTop10ReportVO().builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,",")).build();
    }

    @Override
    public void getBusine2ssData(HttpServletResponse response) {
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));
        try {
            InputStream in = new FileInputStream(new File("D:\\Projects\\sky-project\\sky-take-out\\sky-server\\src\\main\\resources\\template\\运营数据报表模板.xlsx"));
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue("时间："+dateBegin+"至："+dateEnd);

            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());;
            row.getCell(6).setCellValue(businessData.getNewUsers());

            row=sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            for (int i = 0; i < 30; i++) {
                LocalDate date=dateBegin.plusDays(i);
                LocalDateTime begin=LocalDateTime.of(date,LocalTime.MIN);
                LocalDateTime end=LocalDateTime.of(date,LocalTime.MAX);
                BusinessDataVO businessData1 = workspaceService.getBusinessData(begin, end);
                row=sheet.getRow(7+i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData1.getTurnover());
                row.getCell(3).setCellValue(businessData1.getValidOrderCount());
                row.getCell(4).setCellValue(businessData1.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData1.getUnitPrice());
                row.getCell(6).setCellValue(businessData1.getNewUsers());
            }
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);


        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
